<template>
  <div class="app-container">
    <div class="cardBox">
      <div style="display: flex" :gutter="10">
        <div style="flex: 1">
          <el-button
            @click="gobackWay"
            type="text"
            icon="el-icon-arrow-left"
            style="color: rgba(0, 0, 0, 0.85)"
            >返回</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <span>抽奖活动奖品</span>
        </div>
      </div>
    </div>
    <div class="cardBox" style="margin-top: 20px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-button
            v-hasPermi="'raffle/save'"
            icon="el-icon-plus"
            size="small"
            type="primary"
            @click="saveWay('/activity/raffle/save')"
            >添加抽奖活动奖品</el-button
          >
        </el-col>
        <el-col :span="8" style="float: right">
          <div class="right-panel el-button-group">
            <el-button
              class=""
              icon="el-icon-refresh"
              size="mini"
              @click="getListWay"
            ></el-button>
            <el-dropdown trigger="click" :hide-on-click="false">
              <span class="el-dropdown-link">
                <el-button
                  class=""
                  icon="el-icon-s-operation"
                  size="mini"
                ></el-button>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="fruit in allTableThead" :key="fruit">
                  <el-checkbox v-model="checkboxTableThead" :label="fruit">{{
                    tableTheadOptions[fruit].label
                  }}</el-checkbox>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </el-col>
      </el-row>
      <el-col class="marginTop">
        <el-table
          v-loading="loading"
          highlight-current-row
          :data="dataList"
          :header-cell-style="{
            'background-color': '#f3f8fe',
            color: '#606266',
            height: '50px',
          }"
          style="width: 100%"
        >
          <el-table-column
            v-for="fruit in tableThead"
            :key="fruit"
            :label="tableTheadOptions[fruit].label"
            min-width="80"
            align="center"
          >
            <template slot-scope="scope">
              <div v-if="fruit == 'status'">
                <el-tag v-if="scope.row.status == -1" type="danger"
                  >活动结束</el-tag
                >
                <el-tag v-if="scope.row.status == 1" type="success"
                  >已开启</el-tag
                >
                <el-tag v-if="scope.row.status == 3" type="warning"
                  >已关闭</el-tag
                >
                <el-tag v-if="scope.row.status == 2" type="success"
                  >进行中</el-tag
                >
              </div>
              <div v-else-if="fruit == 'image'">
                <div style="width: 40px; height: 40px; margin: 0 auto">
                  <el-image
                    v-if="scope.row.image"
                    :src="scope.row.image"
                    :preview-src-list="[scope.row.image]"
                  />
                </div>
              </div>
              <div v-else-if="fruit == 'award_type'">
                <el-tag v-if="scope.row.status == 1" type="primary"
                  >积分</el-tag
                >
                <el-tag v-if="scope.row.status == 2" type="primary"
                  >提货劵</el-tag
                >
                <el-tag v-if="scope.row.status == 3" type="primary"
                  >提货券比例范围</el-tag
                >
                <el-tag v-if="scope.row.status == 4" type="primary"
                  >未中奖</el-tag
                >
              </div>
              <div v-else-if="fruit == 'user_condition'">
                <el-tag v-if="scope.row.status == 1" type="primary"
                  >用户已购订单数量</el-tag
                >
                <el-tag v-if="scope.row.status == 2" type="primary"
                  >用户已购订单金额</el-tag
                >
                <el-tag v-if="scope.row.status == 3" type="primary"
                  >用户下单获得积分</el-tag
                >
                <el-tag v-if="scope.row.status == 4" type="primary"
                  >用户可用积分范围</el-tag
                >
              </div>
              <div v-else>
                {{ scope.row[fruit] }}
              </div>
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            width="240"
            prop="address"
            label="操作"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                v-hasPermi="'raffle/status'"
                style="margin: 5px"
                v-if="scope.row.status == 1 || scope.row.status == 2"
                type="warning"
                size="mini"
                @click="saveStatus(scope.row, 3)"
              >
                禁用
              </el-button>
              <el-button
                v-hasPermi="'raffle/status'"
                style="margin: 5px"
                v-if="scope.row.status == 3"
                type="success"
                size="mini"
                @click="saveStatus(scope.row, 1)"
              >
                启用
              </el-button>
              <el-button
                v-hasPermi="'raffle/edit'"
                :disabled="scope.row.status == 2"
                style="margin: 5px"
                type="primary"
                size="mini"
                @click="editCoupon(scope.row)"
              >
                编辑
              </el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @confirm="deleteCoupon(scope.row)"
              >
                <el-button
                  v-hasPermi="'raffle/del'"
                  :disabled="scope.row.status == 2"
                  style="margin: 5px"
                  type="danger"
                  size="mini"
                  slot="reference"
                >
                  删除
                </el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </div>

    <el-dialog
      title="添加/编辑活动奖品"
      :visible.sync="ruleDialog"
      width="1000px"
      @close="ruleClose"
    >
      <div style="position: relative" v-loading="ruleloading">
        <el-form
          :model="ruleFrom"
          :rules="ruleRules"
          ref="ruleFrom"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-col :span="23" class="splitTitle">
            <div class="split" style="margin-top: 0">基本内容</div>
          </el-col>
          <el-col :span="11">
            <el-form-item label="奖品模版" prop="templateId">
              <el-select
                style="width: 100%"
                @change="templateIdWay"
                v-model="templateId"
                filterable
                remote
                clearable
                reserve-keyword
                placeholder="请输入模版名称搜索奖品模版"
                :remote-method="remoteMethod"
                :loading="templateLoading"
              >
                <el-option
                  v-for="item in templateList"
                  :key="item.id"
                  :label="item.template_name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="奖品名称" prop="rule_name">
              <el-input
                placeholder="请输入奖品名称"
                v-model="ruleFrom.rule_name"
                maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="类型" prop="award_type">
              <el-radio-group v-model="ruleFrom.award_type">
                <el-radio :label="1">积分</el-radio>
                <el-radio :label="2">提货劵</el-radio>
                <el-radio :label="3">提货券比例范围</el-radio>
                <el-radio :label="99">未中奖</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="提示语" prop="language">
              <el-input
                placeholder="请输入提示语"
                v-model="ruleFrom.language"
                maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="奖品数量" prop="num">
              <el-input
                placeholder="请输入奖品数量"
                v-model="ruleFrom.num"
                maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="中奖率" prop="rule_rate">
              <el-input
                placeholder="请输入中奖率"
                v-model="ruleFrom.rule_rate"
                maxlength="3"
              >
                <span slot="append">%</span></el-input
              >
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="库存" prop="rule_inventory">
              <el-input
                placeholder="请输入库存"
                v-model="ruleFrom.rule_inventory"
                maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="图片" prop="image">
              <logo-upload
                :single-file="image"
                :show-file-list="false"
                accept="image/jpeg, image/png"
                @uploadCallback="imageCallback"
              />
            </el-form-item>
          </el-col>
          <el-col :span="23" class="splitTitle" style="margin-top: 0">
            <div class="split" style="margin-top: 0">规则</div>
          </el-col>

          <el-col :span="22">
            <el-form-item label="条件范围" prop="user_condition">
              <el-radio-group v-model="ruleFrom.user_condition">
                <el-radio style="margin: 10px 10px 10px 0px" :label="0"
                  >全部</el-radio
                >
                <el-radio style="margin: 10px 10px 10px 0px" :label="1"
                  >已购订单数量</el-radio
                >
                <el-radio style="margin: 10px 10px 10px 0px" :label="2"
                  >订单金额</el-radio
                >
                <el-radio style="margin: 10px 10px 10px 0px" :label="3"
                  >用户下单获得积分</el-radio
                >
                <el-radio style="margin: 10px 10px 10px 0px" :label="4"
                  >可用积分范围</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24" v-for="(item, index) in rule_section" :key="index">
          
        </el-col> -->
        </el-form>

        <el-col :span="24" v-for="(item, index) in rule_section" :key="index">
          <el-form
            :model="item"
            ref="rule_section"
            label-width="80px"
            class="demo-ruleForm"
          >
            <el-col :span="5">
              <el-form-item
                label="最小值"
                prop="user_range_min"
                :rules="{
                  required: true,
                  validator: user_range_min,
                  trigger: 'blur',
                }"
              >
                <el-input
                  placeholder="..."
                  v-model="item.user_range_min"
                  maxlength="7"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item
                label="最大值"
                prop="user_range_max"
                :rules="{
                  required: true,
                  validator: user_range_min,
                  trigger: 'blur',
                }"
              >
                <el-input
                  placeholder="..."
                  v-model="item.user_range_max"
                  maxlength="7"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item
                label="最小比例"
                prop="coupon_ratio_min"
                :rules="{
                  required: true,
                  validator: coupon_ratio_min,
                  trigger: 'blur',
                }"
              >
                <el-input
                  placeholder="..."
                  v-model="item.coupon_ratio_min"
                  maxlength="5"
                >
                  <span slot="append">%</span>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item
                label="最大比例"
                prop="coupon_ratio_max"
                :rules="{
                  required: true,
                  validator: coupon_ratio_min,
                  trigger: 'blur',
                }"
              >
                <el-input
                  placeholder="..."
                  v-model="item.coupon_ratio_max"
                  maxlength="5"
                >
                  <span slot="append">%</span>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="text-align: center">
              <el-button
                @click="addrule_section"
                type="primary"
                icon="el-icon-plus"
                circle
              ></el-button>
              <el-button
                @click="delRuleWay(item)"
                v-if="rule_section.length > 1"
                type="danger"
                icon="el-icon-minus"
                circle
              ></el-button>
            </el-col>
          </el-form>
        </el-col>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button :loading="ruleloading" @click="ruleDialog = false"
          >取 消</el-button
        >
        <el-button :loading="ruleloading" type="primary" @click="ruleSubmitWay"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAwardTemplateList,
  SaveAwardRule,
  getAwardRuleList,
  getAwardRuleInfo,
  SaveAwardRuleStatus,
  delAwardRuleStatus,
} from "@/api/activity/index";
import LogoUpload from "@/components/FileUpload";

const tableTheadOption = {
  id: {
    label: "ID",
    field: "id",
  },
  created_at: {
    label: "创建时间",
    field: "created_at",
  },
  rule_name: {
    label: "奖池物品名称",
    field: "rule_name",
  },
  image: {
    label: "图片",
    field: "image",
  },
  award_type: {
    label: "类型",
    field: "award_type",
  },
  num: {
    label: "奖品数量",
    field: "num",
  },
  language: {
    label: "提示语",
    field: "language",
  },
  user_condition: {
    label: "用户条件范围",
    field: "user_condition",
  },
  status: {
    label: "状态",
    field: "status",
  },
};
const allTableThead = [
  "id",
  "created_at",
  "rule_name",
  "image",
  "award_type",
  "num",
  "language",
  "user_condition",
  "status",
];
const defaultTableThead = [
  "created_at",
  "rule_name",
  "image",
  "award_type",
  "num",
  "language",
  "user_condition",
  "status",
];
export default {
  components: {
    LogoUpload,
  },
  watch: {
    checkboxTableThead(valArr) {
      this.tableThead = this.allTableThead.filter(
        (i) => valArr.indexOf(i) >= 0
      );
      this.tableKey = this.tableKey + 1;
    },
  },
  data() {
    return {
      // 动态显示表头默认表头
      tableTheadOptions: tableTheadOption,
      allTableThead: allTableThead,
      tableThead: defaultTableThead, // 默认表头
      checkboxTableThead: defaultTableThead, // 默认表头值
      tableKey: 1, // 为了保证table 每次都会重渲
      loading: true,
      templateList: [],
      templateId: "",
      searchForm: {
        award_id: "",
      },
      dataList: [],
      total: 0,
      ruleDialog: false,
      ruleloading: false,
      ruleFrom: {
        id: "",
        award_id: "",
        rule_name: "",
        image: "",
        award_type: 1,
        rule_section: [],
        user_condition: 0,
        rule_rate: "",
        language: "",
        num: "",
        rule_inventory: "",
        sort: 0,
      },
      image: {},
      ruleRules: {
        rule_name: [
          {
            required: true,
            validator: (rule, value, callback) => {
              let req = /[^0-9a-zA-Z\u4e00-\u9fa5]/g;
              if (value === "") {
                callback(new Error("请输入奖品名称"));
              } else {
                if (req.test(value)) {
                  callback(new Error("奖品名称中不能存在特殊字符"));
                } else {
                  callback();
                }
              }
            },
            trigger: "change",
          },
        ],
        language: [
          {
            required: true,
            validator: (rule, value, callback) => {
              let req = /[^0-9a-zA-Z\u4e00-\u9fa5]/g;
              if (value === "") {
                callback(new Error("请输入提示语"));
              } else {
                if (req.test(value)) {
                  callback(new Error("提示语中不能存在特殊字符"));
                } else {
                  callback();
                }
              }
            },
            trigger: "change",
          },
        ],
        num: [
          {
            required: true,
            validator: (rule, value, callback) => {
              let req = /\D/g;
              if (value === "") {
                callback(new Error("请输入提奖品数量"));
              } else {
                if (req.test(value)) {
                  callback(new Error("奖品数量只能为数字,且只能为整数"));
                } else {
                  callback();
                }
              }
            },
            trigger: "change",
          },
        ],
        rule_rate: [
          {
            required: true,
            validator: (rule, value, callback) => {
              // let req = /\D/g;
              let reqs = /^\d+(\.\d{1,2})?$/;
              if (value === "") {
                callback(new Error("请输入中奖率"));
              } else {
                if (!reqs.test(value)) {
                  callback(new Error("中奖率只能为数字,且不能大于100小于0"));
                } else {
                  if (Number(value) <= 100 && Number(value) >= 0) {
                    callback();
                  } else {
                    callback(new Error("中奖率只能为数字,且不能大于100小于0"));
                  }
                }
              }
            },
            trigger: "change",
          },
        ],
        rule_inventory: [
          {
            required: true,
            validator: (rule, value, callback) => {
              let req = /\D/g;
              if (value === "") {
                callback(new Error("请输入库存"));
              } else {
                if (req.test(value)) {
                  callback(new Error("库存只能为数字,且只能为整数"));
                } else {
                  callback();
                }
              }
            },
            trigger: "change",
          },
        ],
        image: [
          {
            required: true,
            validator: (rule, value, callback) => {
              let req = /\D/g;
              if (this.ruleFrom.image === "") {
                return callback(new Error("请上传图片"));
              }
              callback();
            },
            trigger: "change",
          },
        ],
        award_type: [
          {
            required: true,
            validator: (rule, value, callback) => {
              let req = /\D/g;
              if (value === "") {
                return callback(new Error("请选择"));
              }
              callback();
            },
            trigger: "change",
          },
        ],
        user_condition: [
          {
            required: true,
            validator: (rule, value, callback) => {
              let req = /\D/g;
              if (value === "") {
                return callback(new Error("请选择"));
              }
              callback();
            },
            trigger: "change",
          },
        ],
      },
      templateLoading: false,
      rule_sectionRules: {},
      rule_section: [
        {
          id: 0,
          user_range_min: "",
          user_range_max: "",
          coupon_ratio_min: "",
          coupon_ratio_max: "",
        },
      ],
      user_range_min: function (rule, value, callback) {
        let req = /^\d+(\.\d{1,2})?$/;
        if (value === "") {
          return callback(new Error("请输入数值"));
        } else {
          if (!req.test(value)) {
            return callback(new Error("数值只能为数字,最多两位小数"));
          } else {
            callback();
          }
        }
      },
      coupon_ratio_min: function (rule, value, callback) {
        let req = /^\d+(\.\d{1,2})?$/;
        if (value === "") {
          return callback(new Error("请输入数值"));
        } else {
          if (!req.test(value)) {
            return callback(new Error("数值只能为数字,最多两位小数"));
          } else {
            if (Number(value) > 100) {
              callback(new Error("请输入0-100"));
            } else {
              callback();
            }
          }
        }
      },
    };
  },
  created() {
    this.searchForm.award_id = this.$route.query.pId;
    this.ruleFrom.award_id = this.$route.query.pId;
    getAwardTemplateList({ page: 1, count: 10 }).then((res) => {
      if (res.code !== 200 || res.status !== 1) {
        this.loading = false;
        return this.$messages.error(res.msg);
      }
      this.templateList = res.data.list;
      this.getListWay();
    });
  },
  methods: {
    getListWay() {
      this.loading = true;
      getAwardRuleList(this.searchForm).then((res) => {
        this.loading = false;
        if (res.code !== 200 || res.status !== 1) {
          this.loading = false;
          return this.$messages.error(res.msg);
        }
        this.dataList = res.data;
        this.total = res.data.total;
      });
    },
    resetting() {},

    deleteCoupon(row) {
      this.loading = true;
      delAwardRuleStatus({ id: row.id })
        .then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            this.loading = false;
            return this.$messages.error(res.msg);
          }
          this.$messages.success("删除成功");
          this.getListWay();
        })
        .catch((err) => {
          this.loading = false;
          this.$messages.error(err.msg);
        });
    },
    saveStatus(row, num) {
      var obj = {
        id: row.id,
        status: num,
      };
      this.loading = true;
      SaveAwardRuleStatus(obj)
        .then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            this.loading = false;
            return this.$messages.error(res.msg);
          }
          this.$messages.success("操作成功");
          this.getListWay();
        })
        .catch((err) => {
          this.$messages.error(err.msg);
          this.loading = false;
        });
    },
    remoteMethod(text) {
      this.templateLoading = true;
      getAwardTemplateList({ page: 1, count: 10, template_name: text }).then(
        (res) => {
          this.templateLoading = false;
          if (res.code !== 200 || res.status !== 1) {
            return this.$messages.error(res.msg);
          }
          this.templateList = res.data.list;
        }
      );
    },
    templateIdWay(val) {
      this.templateList.forEach((item) => {
        if (item.id == val) {
          this.ruleFrom.rule_name = item.template_name;
          this.ruleFrom.image = item.image;
          this.image = {
            url: item.image,
          };
          this.ruleFrom.award_type = item.type;
          this.ruleFrom.language = item.language;
        }
      });
    },
    imageCallback(file) {
      this.image = file;
      this.ruleFrom.image = file.url;
    },
    editCoupon(row) {
      this.saveWay();
      this.ruleloading = true;
      getAwardRuleInfo({ id: row.id }).then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.ruleloading = false;
          return this.$messages.error(res.msg);
        }
        this.ruleFrom.id = res.data.id;
        this.ruleFrom.award_id = res.data.award_id;
        this.ruleFrom.rule_name = res.data.rule_name;
        this.ruleFrom.image = res.data.image;
        this.image = {
          url: res.data.image,
        };
        this.ruleFrom.award_type = res.data.award_type;
        this.ruleFrom.user_condition = res.data.user_condition;
        this.ruleFrom.language = res.data.language;
        this.ruleFrom.num = Number(res.data.num);
        this.ruleFrom.rule_rate = res.data.rule_rate;
        this.ruleFrom.rule_inventory = res.data.rule_inventory;
        this.ruleFrom.sort = res.data.sort;
        this.rule_section = res.data.rule_section;
        this.ruleloading = false;
      });
    },
    saveWay() {
      this.ruleDialog = true;
      this.ruleClose();
    },
    addrule_section() {
      this.rule_section.push({
        id: this.rule_section.length + "" + new Date().getTime(),
        user_range_min: "",
        user_range_max: "",
        coupon_ratio_min: "",
        coupon_ratio_max: "",
      });
    },
    delRuleWay(row) {
      var arr = [];
      this.rule_section.forEach((item) => {
        if (item.id !== row.id) {
          arr.push(item);
        }
      });
      this.rule_section = arr;
    },
    ruleClose() {
      this.ruleFrom = {
        id: "",
        award_id: "",
        rule_name: "",
        image: "",
        award_type: 1,
        rule_section: [],
        user_condition: 0,
        rule_rate: "",
        language: "",
        num: "",
        rule_inventory: "",
        sort: 0,
      };
      this.image = {};
      this.rule_section = [
        {
          id: 0,
          user_range_min: "",
          user_range_max: "",
          coupon_ratio_min: "",
          coupon_ratio_max: "",
        },
      ];
      if (this.$refs.ruleFrom) {
        this.$refs.ruleFrom.resetFields();
      }
    },
    ruleSubmitWay() {
      const p1 = new Promise((req, rej) => {
        this.$refs.ruleFrom.validate((valid) => {
          if (valid) {
            req();
          } else {
            rej();
            return false;
          }
        });
      });
      const p2 = new Promise((req, rej) => {
        this.rule_section.some((item, index) => {
          if (item.user_range_min == "") {
            this.$messages.error("请填写第" + (index + 1) + "条中的最小值");
            rej();
            return true;
          }
          if (item.user_range_max == "") {
            this.$messages.error("请填写第" + (index + 1) + "条中的最大值");
            rej();
            return true;
          }
          if (item.coupon_ratio_min == "") {
            this.$messages.error("请填写第" + (index + 1) + "条中的最小比例");
            rej();
            return true;
          }
          if (item.coupon_ratio_max == "") {
            this.$messages.error("请填写第" + (index + 1) + "条中的最大比例");
            rej();
            return true;
          }
        });
        req();
      });
      Promise.all([p1, p2])
        .then(() => {
          var obj = {
            ...this.ruleFrom,
          };
          obj.rule_section = JSON.stringify(this.rule_section);
          obj.award_id = this.$route.query.pId;
          this.ruleloading = true;
          SaveAwardRule(obj).then((res) => {
            this.ruleloading = false;
            if (res.code !== 200 || res.status !== 1) {
              return this.$messages.error(res.msg);
            }
            this.$messages.success(res.msg);
            this.ruleClose();
            this.ruleDialog = false;
            this.getListWay();
          });
        })
        .catch(() => {
          console.log("不操作");
        });
    },
    gobackWay() {
      this.$router.push("/activity/raffle");
    },
  },
};
</script>

<style>
</style>